package cn.joeg.app.web.core.auth;

import cn.joeg.app.GCore;
import cn.joeg.app.dto.OptInfo;
import com.ecfront.dew.common.JsonHelper;

import java.util.concurrent.locks.ReentrantLock;

public class CacheManager {

    private static ReentrantLock tokenLock = new ReentrantLock();

    public static void addToken(OptInfo optInfo) {
        tokenLock.lock();
        removeTokenByLoginId(optInfo.getLoginId() + ":" + optInfo.getAccountCode());
        GCore.cluster.cache.set(GCore.Constant.TOKEN_ID_REL_FLAG + optInfo.getLoginId() + ":" + optInfo.getAccountCode(), optInfo.getToken());
        GCore.cluster.cache.set(GCore.Constant.TOKEN_INFO_FLAG + optInfo.getToken(), JsonHelper.toJsonString(optInfo));
        tokenLock.unlock();
    }

    public static void removeTokenByLoginId(String loginId) {
        String token = getToken(loginId);
        if (token != null) {
            removeToken(token);
        }
    }

    public static void removeToken(String token) {
        OptInfo tokenInfo = getTokenInfo(token);
        if (tokenInfo != null) {
            GCore.cluster.cache.del(GCore.Constant.TOKEN_ID_REL_FLAG + tokenInfo.getLoginId() + ":" + tokenInfo.getAccountCode());
            GCore.cluster.cache.del(GCore.Constant.TOKEN_INFO_FLAG + token);
        }
    }

    public static String getToken(String loginId) {
        return GCore.cluster.cache.get(GCore.Constant.TOKEN_ID_REL_FLAG + loginId);
    }

    public static OptInfo getTokenInfo(String token) {
        return JsonHelper.toObject(GCore.cluster.cache.get(GCore.Constant.TOKEN_INFO_FLAG + token), OptInfo.class);
    }


}
